package com.leyou.page.service.impl;

import com.leyou.item.pojo.*;
import com.leyou.page.client.BrandClient;
import com.leyou.page.client.CategoryClient;
import com.leyou.page.client.GoodsClient;
import com.leyou.page.client.SpecificationClient;
import com.leyou.page.service.PageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.io.File;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName PageServiceImpl
 * @Date 2019/2/21 15:35
 */
@Slf4j
@Service
public class PageServiceImpl implements PageService {

    @Autowired
    private BrandClient brandClient;
    
    @Autowired
    private CategoryClient categoryClient;
    
    @Autowired
    private GoodsClient goodsClient;
    
    @Autowired
    private SpecificationClient specClient;

    @Autowired
    private TemplateEngine templateEngine;
    
    @Override
    public Map<String, Object> loadModel(Long id) {
        Map<String, Object> map = new HashMap<>();
        //查询spu
        Spu spu = goodsClient.querySpuById(id);
        //查询skus
        List<Sku> skus = goodsClient.querySkuBySpuId(id);
        //查询detail
        SpuDetail detail = goodsClient.queryDetail(id);
        //查询brand
        Brand brand = brandClient.queryBrandById(spu.getBrandId());
        //查询categorites
        List<Category> categories = categoryClient.queryCategoryByIds(Arrays.asList(spu.getCid1(), spu.getCid2(), spu.getCid3()));
        //查询specs
        List<SpecGroup> specs = specClient.queryGroupsByCid(spu.getCid3());
        map.put("title", spu.getTitle());
        map.put("subTitle", spu.getSubTitle());
        map.put("skus", skus);
        map.put("detail", detail);
        map.put("brand", brand);
        map.put("categories", categories);
        map.put("specs", specs);
        return map;
    }

    public void createHTML(Long spuId) {
        //上下文
        Context context = new Context();
        context.setVariables(loadModel(spuId));
        //输出流
        File file = new File("E:/Work4IDEA/leyou/upload", spuId+".html");
        if (file.exists()) {
            file.delete();
        }
        try {
            PrintWriter printWriter = new PrintWriter(file, "UTF-8");
            //生成HTML
            templateEngine.process("item", context, printWriter);
        } catch (Exception e) {
            log.error("[生成静态页面失败]", e);
        }
    }

    public void deleteHTML(Long spuId) {
        File file = new File("E:/Work4IDEA/leyou/upload", spuId+".html");
        if (file.exists()) {
            file.delete();
        }
    }
}
